package com.chy.srb.sms.service.impl;

import com.alibaba.fastjson.JSON;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.dysmsapi20170525.models.SendSmsResponseBody;
import com.aliyun.teaopenapi.models.Config;
import com.chy.srb.common.exception.Assert;
import com.chy.srb.common.result.ResponseEnum;
import com.chy.srb.sms.service.SmsService;
import com.chy.srb.sms.util.SmsProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @Author: chenhy
 * @Date: 2022年01月21日
 */
@Slf4j
@Service
public class SmsServiceImpl implements SmsService {

    private Client createClient() throws Exception {
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(SmsProperties.KEY_ID)
                // 您的AccessKey Secret
                .setAccessKeySecret(SmsProperties.KEY_SECRET);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new Client(config);
    }

    @Override
    public void send(String mobile, String templateCode, Map<String, Object> param) throws Exception {
        // 老版写法
        /*// 创建远程连接客户端对象
        DefaultProfile profile = DefaultProfile.getProfile(
                SmsProperties.REGION_ID,
                SmsProperties.KEY_ID,
                SmsProperties.KEY_SECRET);
        IAcsClient client = new DefaultAcsClient(profile);

        // 创建远程连接的请求参数
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", SmsProperties.REGION_ID);
        request.putQueryParameter("PhoneNumbers", mobile);
        request.putQueryParameter("SignName", SmsProperties.SIGN_NAME);
        request.putQueryParameter("TemplateCode", templateCode);

        String jsonParam = JSON.toJSONString(param);
        request.putQueryParameter("TemplateParam", jsonParam);
        try {
            // 使用客户端对象携带请求参数向远程阿里云服务器发起远程调用，并得到响应结果
            CommonResponse response = client.getCommonResponse(request);
            System.out.println("response.getData()：" + response.getData());

            // 通信失败的处理
            boolean success = response.getHttpResponse().isSuccess();
            Assert.isTrue(success, ResponseEnum.ALIYUN_RESPONSE_ERROR);

            // 获取响应结果
            String data = response.getData();
            HashMap<String, String> resultMap = JSON.parseObject(data, new TypeReference<HashMap<String, String>>(){});
            String code = resultMap.get("Code");
            String message = resultMap.get("Message");
            log.info("code：" + code + "，message：" + message);

            // 业务失败的处理
            Assert.notEquals("isv.BUSINESS_LIMIT_CONTROL", code, ResponseEnum.ALIYUN_SMS_LIMIT_CONTROL_ERROR);
            Assert.equals("OK", code, ResponseEnum.ALIYUN_SMS_ERROR);
        } catch (ClientException e) {
            log.error("阿里云短信发送sdk调用失败:" + e.getErrCode() + ", " + e.getErrMsg());
            throw new BusinessException(ResponseEnum.ALIYUN_SMS_ERROR, e);
        }*/

        // 新版写法
        Client client = createClient();
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setPhoneNumbers(mobile)
                .setSignName(SmsProperties.SIGN_NAME)
                .setTemplateCode(SmsProperties.TEMPLATE_CODE)
                .setTemplateParam(JSON.toJSONString(param));
        // 复制代码运行请自行打印 API 的返回值
        SendSmsResponse response = client.sendSms(sendSmsRequest);
        // 获取响应结果
        SendSmsResponseBody responseBody = response.getBody();
        String code = responseBody.getCode();
        log.info("短信发送响应结果: " +
                "requestId: " + responseBody.requestId +
                ", bizId: " + responseBody.bizId +
                ", code: " + responseBody.code +
                ", message: " + responseBody.message);

        // 业务失败的处理
        Assert.notEquals("isv.BUSINESS_LIMIT_CONTROL", code, ResponseEnum.ALIYUN_SMS_LIMIT_CONTROL_ERROR);
        Assert.equals("OK", code, ResponseEnum.ALIYUN_SMS_ERROR);
    }
}
